package com.xxk.wdis.utills;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 拼音工具类,用于汉字转拼音
 */
public class PinYinUtils {
    private static final Logger logger = LoggerFactory.getLogger(PinYinUtils.class);

    /**
     * 对单个字进行转换,得到小写全拼音
     *
     * @param pinYinStr
     * @return 拼音字符串数组
     */
    public static String getStringPinYin(String pinYinStr) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        StringBuilder convert = new StringBuilder();
        try {
            for (int i = 0; i < pinYinStr.length(); i++) {
                char word = pinYinStr.charAt(i);
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word, format);
                if (pinyinArray != null) {
                    convert.append(pinyinArray[0]);
                } else {
                    convert.append(word);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e1) {
            e1.printStackTrace();
            logger.error("字符串转拼音失败", e1);
        }

        return convert.toString().toLowerCase();
    }

    /**
     * 得到中文首字母
     *
     * @param str 汉字字符串
     * @return String 小写拼音首字母
     */
    public static String getPinYinHeadChar(String str) {
        StringBuilder convert = new StringBuilder();
        for (int i = 0; i < str.length(); i++) {
            char word = str.charAt(i);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                //输出首位
                convert.append(pinyinArray[0].charAt(0));
            } else {
                convert.append(word);
            }
        }
        return convert.toString().toLowerCase();
    }

}
